<template>
  <div class="app-container">
    <div
      v-show="!modifyInfo.visible && !detailsInfo.visible"
      v-if="proxy.$permission('assetDict:list')"
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-run>
            <el-button :disabled="!canRun" @click="batchEnableEquipment()"
              >启用</el-button
            >
          </template>
          <template v-slot:filter-stop>
            <el-button :disabled="!canStop" @click="batchDisableEquipment()"
              >停用</el-button
            >
          </template>
          <template v-slot:filter-print>
            <el-button
              :disabled="!tableInfo.selections.length"
              @click="printEquipmentCode()"
              >打印编码</el-button
            >
          </template>
          <template v-slot:filter-upload>
            <el-button style="marginleft: 10px" @click="uploadImg"
              >上传图片</el-button
            >
          </template>
          <template v-slot:filter-uploadProduct>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-exprotExcel>
            <el-button @click="exportExcel">导出excel</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <Group-select
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelectCallBack"
            @callbackVal="updateGroupSelections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true"
            >偏好设置
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :isGroupSearch="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :checkBox="false"
        :tabIndex="false"
        :pager="false"
        :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
      >
        <template
          v-slot:col-commonName="scope"
          v-if="proxy.$permission('assetDict:detail')"
        >
          {{ scope.row.commonName }}
        </template>
        <template v-slot:col-commonName="scope" v-else>
          {{ scope.row.commonName }}
        </template>
      </table-container>
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="true"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassOtherName"
        @sortChange="sortChange"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template
          v-slot:col-commonName="scope"
          v-if="proxy.$permission('assetDict:detail')"
        >
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.commonName || '-'
          }}</span>
        </template>
        <template v-slot:col-commonName="scope" v-else>
          {{ scope.row.commonName }}
        </template>
      </table-container>
    </div>
    <!--偏好 -->
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <!-- 详情-->
    <equipment-archives-details
      v-if="detailsInfo.visible"
      v-model:visible="detailsInfo.visible"
      :title="detailsInfo.title"
      :id="detailsInfo.id"
      @returnBack="getList"
    />
    <!-- 新增或修改 -->
    <equipment-archives-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
      :id="modifyInfo.id"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />

    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <chose-printer
      :visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
    <DialogUpload
      v-if="dialogUploadInfo.visible"
      v-model:show-dialog="dialogUploadInfo.visible"
      :vaildate-api="dialogUploadInfo.vaildateApi"
      :api="dialogUploadInfo.api"
      @callback="getList"
    >
    </DialogUpload>
  </div>
</template>

<script setup name="assetDict">
import {
  downloadFileAssetDict,
  getEquipmentArchivesCustomizePage,
  getEquipmentArchivesDetailCustomizeGroups,
  getEquipmentArchivesDetailCustomizeList,
  enableEquipmentArchives,
  disableEquipmentArchives,
  exportEquipmentArchives,
  printEquipmentArchivesCode,
  equipmentArchivesFile,
  equipmentArchivesVaildateFile,
} from '@/api/equipment'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import axios from 'axios'
import { ElLoading } from 'element-plus'
import { fatchTemplateByCode } from '@/api/base'
import { exportTemplateExcel } from '@/api/pub.js'
import EquipmentArchivesModify from './modify'
import EquipmentArchivesDetails from './details'

const { proxy } = getCurrentInstance()
const dialogUploadInfo = ref({
  visible: false,
  api: equipmentArchivesFile,
  vaildateApi: equipmentArchivesVaildateFile,
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      type: {
        asTbName: 'core_product_new',
        columnName: '`type`',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '1',
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetDict:add'),
    },
    {
      type: 'slot',
      value: 'run',
      show: proxy.$permission('assetDict:add'),
    },
    {
      type: 'slot',
      value: 'stop',
      show: proxy.$permission('assetDict:stop'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetDict:print'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('assetDict:download'),
    },
    {
      type: 'slot',
      value: 'uploadProduct',
      show: proxy.$permission('assetDict:import'),
    },
    {
      type: 'slot',
      value: 'upload',
      show: proxy.$permission('assetDict:upload'),
    },
    {
      type: 'button',
      label: '下载图片',
      event: downloadFile,
      show: proxy.$permission('assetDict:downloadFile'),
    },
    {
      type: 'slot',
      label: '导出excel',
      value: 'exprotExcel',
      show: proxy.$permission('assetDict:export'),
    },
  ],
})
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetDict:update'),
      },
      {
        label: '启用',
        event: batchEnableEquipment,
        show: proxy.$permission('assetDict:run'),
        ifRender(row) {
          return row.status === 0
        },
      },
      {
        label: '停用',
        event: batchDisableEquipment,
        show: proxy.$permission('assetDict:stop'),
        ifRender(row) {
          return row.status === 1
        },
      },
    ],
  },
})
const time = ref([])
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const detailsInfo = ref({
  visible: false,
  id: '',
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const preferenceInfo = ref({
  visible: false,
})
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/asset/setting/assetDict/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '导出',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const canRun = computed(() => {
  return (
    tableInfo.value.selections.length > 0 &&
    tableInfo.value.selections.filter((item) => item.status === 1).length === 0
  )
})
const canStop = computed(() => {
  return (
    tableInfo.value.selections.length > 0 &&
    tableInfo.value.selections.filter((item) => item.status === 0).length === 0
  )
})

let obj = ref({
  commonName: {
    label: '名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    type: 'slot',
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'new_enabled_type',
    show: false,
    hidden: true,
  },
  picture: {
    label: '图片',
    value: 'picture',
    componentType: 'input',
    type: 'showImage',
    show: false,
    hidden: true,
  },
  trademark: {
    label: '品牌',
    value: 'trademark',
    componentType: 'input',
    type: 'column',
    show: false,
    hidden: true,
  },
  maintenanceCode: {
    label: '维保商编码',
    value: 'maintenanceCode',
    componentType: 'input',
    type: 'column',
    show: false,
    hidden: true,
  },
  deprMethodTypeValue: {
    label: '折旧方法',
    value: 'deprMethodTypeValue',
    asValue: 'deprMethodType',
    componentType: 'select-model',
    code: 'depr_method_type',
    show: false,
    hidden: true,
  },
})
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
})

function downloadFile() {
  downloadFileAssetDict(filterInfo.value.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function pageInfo(obj) {
  page.value = obj
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  exportEquipmentArchives(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assCard:printListCard',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function handleClose() {
  dialogInfo.value.visible = false
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
// 创建
function create() {
  modifyInfo.value.id = ''
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增资产字典'
}
// 编辑
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改资产字典'
}

function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
}

function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailsInfo.value.id = row.id
  detailsInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function tableRowClassName({ row }) {
  if (row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function tableRowClassOtherName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey: 'assetDictList-com.slip.spd.entity.vo.asset.settings.AssetDictVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getEquipmentArchivesCustomizePage
      getList()
    }
  })
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getEquipmentArchivesDetailCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getEquipmentArchivesDetailCustomizeList(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function groupSelectCallBack(arr) {
  //点击分组
  if (arr.length) {
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    proxy.$message.warning({
      message: '请选择分组条件',
      show: true,
      duration: 3000,
    })
  }
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
function downloadTemplate() {
  exportTemplateExcel('asset_dict_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function batchEnableEquipment(row) {
  const ids = getIds(row)
  enableEquipmentArchives(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function batchDisableEquipment(row) {
  const ids = getIds(row)
  disableEquipmentArchives(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function uploadImg() {
  dialogUploadInfo.value.visible = true
}
function printEquipmentCode(row) {
  let data = []
  if (row && row.id) {
    data.push(row.id)
  } else {
    data = tableInfo.value.selections.map((item) => item.id)
  }
  if (data.length) {
    printEquipmentArchivesCode(data).then((res) => {
      if (res && res.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = res.data
      }
    })
  } else {
    proxy.$message({
      message: '选择需要打印的二维码',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  obj.queryDtoList.push({
    fieldName: 'type',
    queryCategory: 'AND',
    queryType: 'EQUALS',
    value: 1,
  })
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  if (groupSelectInfo.value.selections.length > 0) {
    await getCustomizeGroupsList()
  } else {
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
getCustomize()
</script>

<style scoped></style>
